import logging
from lxml import etree
from rest4databases.lib.base import *
from rest4databases.lib.databases import TableNotExistException

log = logging.getLogger(__name__)

class RelationsController(BaseController):
    """REST Controller styled on the Atom Publishing Protocol"""
    # To properly map this controller, ensure your config/routing.py file has
    # a resource setup:
    #     map.resource('relation', 'relations')


    def index(self, format='html'):
        """GET /relations: All items in the collection."""
        # url_for('relations')
        pass

    def create(self):
        """POST /relations: Create a new item."""
        # url_for('relations')
        try:
            content = request.body.read(int(request.environ['CONTENT_LENGTH']))
            tree = etree.fromstring(content)
            type = tree.xpath('/relation/@type')
            tables = tree.xpath('/relation/table')
            if len(tables) != 2:
                abort(400)
            table1 = tables[0].get('name')
            table2 = tables[1].get('name')
            g.database.createRelation(table1, table2, type=type)
            del response.headers['Content-Type']
            response.status_code = 201
            return str('/db/relations/%s/%s' % (table1, table2))
        except TableNotExistException, etree.XMLSyntaxError:
            abort(400)

    def new(self, format='html'):
        """GET /relations/new: Form to create a new item."""
        # url_for('new_relation')
        pass

    def update(self, id):
        """PUT /relations/id: Update an existing item."""
        # Forms posted to this method should contain a hidden field:
        #    <input type="hidden" name="_method" value="PUT" />
        # Or using helpers:
        #    h.form(h.url_for('relation', id=ID),
        #           method='put')
        # url_for('relation', id=ID)
        pass

    def delete(self, id):
        """DELETE /relations/id: Delete an existing item."""
        # Forms posted to this method should contain a hidden field:
        #    <input type="hidden" name="_method" value="DELETE" />
        # Or using helpers:
        #    h.form(h.url_for('relation', id=ID),
        #           method='delete')
        # url_for('relation', id=ID)
        pass

    def show(self, id, format='html'):
        """GET /relations/id: Show a specific item."""
        # url_for('relation', id=ID)
        pass

    def edit(self, id, format='html'):
        """GET /relations/id;edit: Form to edit an existing item."""
        # url_for('edit_relation', id=ID)
        pass
